package cn.com.dreamtouch.magicbox_general_ui.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.util.TypedValue;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by frank on 2016/3/25.
 */
public class Utils {

    public static final String APP_FOLDER_ON_SD = Environment
            .getExternalStorageDirectory().getAbsolutePath()
            + "/api/boss";

    public static final String CACHE_FOLDER = APP_FOLDER_ON_SD
            + "/photo_cache";

    public static int dp2px(Context ctx, float dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                ctx.getResources().getDisplayMetrics());
    }

    /**
     * 查看图片旋转角度
     *
     * @param path
     * @return
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 保存Bitmap到指定的目录下
     *
     * @param bitmap  保存的bitmap
     * @param url     图片网络路径
     * @param isJpg   是否是JPG
     * @param quality 缩放比
     * @return 是否成功
     */
    public static boolean saveBitmapToSDCard(Bitmap bitmap, String url
            , boolean isJpg, int quality) {

        boolean result = false;

        if (bitmap == null) {

            return false;
        }

//        if (FREE_SD_SPACE_NEEDED_TO_CACHE > MiscUtils.freeSpaceOnSd()) {
//            L.w("Low free space onsd, do not cache");
//            return false;
//        }

        if (url == null || (url != null && url.equals(""))) {
            return false;
        }


        File file = new File(url);


        try {
            file.createNewFile();

            OutputStream outStream = new FileOutputStream(file);


            if (isJpg) {
                // 输出
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outStream);
            } else {
                // 输出
                bitmap.compress(Bitmap.CompressFormat.PNG, quality, outStream);
            }

            result = true;

        } catch (IOException e) {

            result = false;

        }
        return result;
    }


    /**
     * 保存Bitmap到指定的目录下
     *
     * @param bitmap  保存的bitmap
     * @param url     图片网络路径
     * @param isJpg   是否是JPG
     * @param quality 缩放比
     * @param degree  旋转
     * @return 是否成功
     */
    public static boolean saveBitmapToSDCard(Bitmap bitmap, String url
            , boolean isJpg, int quality, int degree) {

        boolean result = false;
        if (bitmap == null) {
            return false;
        }

//        if (FREE_SD_SPACE_NEEDED_TO_CACHE > MiscUtils.freeSpaceOnSd()) {
//            L.w("Low free space onsd, do not cache");
//            return false;
//        }

        if (url == null || (url != null && url.equals(""))) {
            return false;
        }


        File file = new File(url);

        try {


            if (0 != degree % 360) {
                Matrix mat = new Matrix();
                mat.postRotate(degree);

                bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                        bitmap.getHeight(), mat, true);
            }

            file.createNewFile();

            OutputStream outStream = new FileOutputStream(file);

            if (isJpg) {
                // 输出
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outStream);
            } else {
                // 输出
                bitmap.compress(Bitmap.CompressFormat.PNG, quality, outStream);
            }

            result = true;

        } catch (Exception e) {
            result = false;
        }
        return result;
    }


    /**
     * 图片缩放处理,并保存到SDCard
     *
     * @param maxSide  目标大小
     * @param localUri 本地图片Uri
     * @param folder   保存文件夹
     * @param degree   旋转角度
     * @return 缩放后的图片bitmap
     */
    public static String saveThumbBitmapToSDCard(String localUri, String folder, int maxSide, int degree) {
        Bitmap tempBitmap = null;
        String path = new String();
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            tempBitmap = BitmapFactory.decodeFile(localUri, options);

            int width = options.outWidth;
            int height = options.outHeight;
            int max = Math.max(width, height);
            int zoomPower = 0;

            while (max > maxSide) {
                zoomPower++;
                max /= Math.pow(2, zoomPower);
            }

            options.inSampleSize = (int) Math.pow(2, zoomPower);
            options.inJustDecodeBounds = false;

            // 重新读入图片,此时为缩放后的图片

            tempBitmap = BitmapFactory.decodeFile(localUri, options);
            if (0 != degree % 360) {
                Matrix mat = new Matrix();
                mat.postRotate(degree);

                tempBitmap = Bitmap.createBitmap(tempBitmap, 0, 0, tempBitmap.getWidth(),
                        tempBitmap.getHeight(), mat, true);
            }
            if (!(new File(folder).exists())) new File(folder).mkdirs();
            Uri uri = Uri.fromFile(new File(localUri));
            path = folder + File.separator + uri.getLastPathSegment();
            saveBitmapToSDCard(tempBitmap, path, true, 80);

        } catch (Exception e) {
        } finally {
            if (tempBitmap != null) {
                tempBitmap.recycle();
            }
        }
        return path;
    }

    /**
     * 判断当前设备是手机还是平板，代码来自 Google I/O App for Android
     * @param context
     * @return 平板返回 True，手机返回 False
     */
    public static boolean   isPad(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * get App versionCode
     *
     * @param context
     * @return
     */
    public static String getVersionCode(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        String versionCode = "";
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionCode = packageInfo.versionCode + "";
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }
}
